package com.lovi.mysql_;

import com.lovi.domain.Actor;
import com.lovi.utils.JDBCUtilsByDruid;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

/**
 * 使用工具包
 */
public class TestJDBCUtilsByDruid {
    @Test
    public void test1() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.getConnection();
        //执行sql
        String sql = "select * from actor";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.print(resultSet.getString("name")+"\t");
            System.out.print(resultSet.getString("sex"));
        }
        //释放资源
        JDBCUtilsByDruid.close(resultSet,preparedStatement,connection);
    }
    //尝试自己处理结果集！
    @Test
    public void test2() throws SQLException {
        //得到连接
        Connection connection = JDBCUtilsByDruid.getConnection();
        //执行sql
        String sql = "select * from actor";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<Actor> actors = new ArrayList<>();
        while (resultSet.next()){
            Integer id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String sex = resultSet.getString("sex");
            Date birthday = resultSet.getDate("birthday");
            String phone = resultSet.getString("phone");
            actors.add(new Actor(id,name,sex,birthday,phone));
        }
        //释放资源
        JDBCUtilsByDruid.close(resultSet,preparedStatement,connection);
        //拿到我们的actors
        actors.forEach(System.out::println);
    }
}
